package com.ps.camera;

import java.io.File;

import org.apache.log4j.Logger;
import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class OpenCVPreview extends SurfaceView implements SurfaceHolder.Callback{
//	private static final String TAG = OpenCVPreview.class.getSimpleName();

	private Handler calculateHandler;
	protected DrawThread drawThread;

	protected Bitmap bitmap;
	Logger log = Logger.getLogger(CameraActivity.class);

	public OpenCVPreview(Context context, AttributeSet attrs) {
		super(context, attrs);
		File storagePath = SLogger.getStoragePath();
		SLogger.loadLogConfigurator(storagePath);
		log.info("OpenCV Preview Loaded");
		
		getHolder().addCallback(this);

		calculateHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				calculate(msg.arg1, msg.arg2, (byte[]) msg.obj);
			}
		};
	}

	protected void calculate(int width, int height, byte[] data) {
		
		//Mat mYuv = new Mat(height + height / 2, width, CvType.CV_8UC3);
		Mat mYuv = new Mat(height + height / 2, width, CvType.CV_8UC1);
		mYuv.put(0, 0, data);
		
		Mat mRgb = new Mat(height, width, CvType.CV_8UC3);
		//COLOR_YUV420sp2RGB
		Imgproc.cvtColor(mYuv, mRgb, Imgproc.COLOR_YUV420sp2RGB, 3);    
		
		if (bitmap == null)
			bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		
		Utils.matToBitmap(mYuv, bitmap);
		            			
		drawThread.setBitmap(bitmap);
		
	};
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		log.info("Surface Created");
		drawThread = new DrawThread(getHolder(), getResources());
		drawThread.setRunning(true);
		drawThread.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		log.info("Surface Destroyed");
		boolean retry = true;
		drawThread.setRunning(false);
		while (retry) {
			try {
				drawThread.join();
				retry = false;
			} catch (InterruptedException e) {

			}
		}
	}

	public Handler getCalculateHandler() {
		return calculateHandler;
	}	
}
